
package com.scalar.chiptrack.operations.packingslip.actions;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLineItem;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLotNumberData;
import com.scalar.chiptrack.operations.packingslip.FinalInventoryData;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.operations.packingslip.dao.CommercialInvoiceDAO;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;

public class PackingSlipAction extends ChipTrackAction
{

    private static String ERROR_MESSAGE_CONTACT_SYS_ADMN = "Please.. Contact <a href='javascript:showErrorReportPage()'>System Administrator</a>";

	private HashMap m_errors = null;

	public PackingSlipAction()
	{
        m_errors = new HashMap();
    }

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

		String returnVal    = "failure";
		String action       = request.getParameter("action");
		if (action == null)
		{
			action = "newPackingSlip";
		}

        request.setAttribute ("AUTO_CONFIRM_PACKING_SLIP", request.getParameter ("autoConfirmPackingSlip"));

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute (SessionKeys.USER_KEY);

        String isRequestFromTrackingNoPage = (String) request.getParameter ( "isReqFromTrackingNoPage" );
        if ( ( isRequestFromTrackingNoPage != null ) && ( isRequestFromTrackingNoPage.equals ( "true" ) ) ) //When request comes from PS Freight Tracking No. Page.
        {
            if( user == null )
            {
                user = new User ();
                user.setUserId ( "vendor" );
                user.setEmail ( ConfigManager.getSysAdminEmail() );
                session.setAttribute ( SessionKeys.USER_KEY , user );
            }
        }

		if (user == null)
		{
            if ( action.equalsIgnoreCase("view") )
            {
                PackingSlipForm packingSlipForm = (PackingSlipForm) form;
                if( packingSlipForm != null && ( packingSlipForm.isCancelPackingSlip() || packingSlipForm.isConfrimPackingSlip() ) )
                {
                    session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, "/searchPackingSlip.do" );
                }
            }
            else
            {
			    session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, "/packingSlip.do?" + request.getQueryString());
            }
			return (mapping.findForward("login"));
        }


		// Redirection to NewPackingSlipAction
		if( true )
		{
			return new NewPackingSlipAction().execute( mapping, form, request, response );
		}
        String currentUser = user.getUserId();

        // CANCEL THIS PACKING SLIP 
		if ("cancelPackingSlip".equalsIgnoreCase (action))
		{
			PackingSlipForm packingSlipForm = ( PackingSlipForm ) form;
			int customerShippingId          = packingSlipForm.getCustomerShippingId();
			DBTransaction dbTransaction     = null;
			boolean success                 = false;
            try
			{
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();
				PackingSlipDAO.cancelPackingSlip( dbTransaction, customerShippingId );
				CommercialInvoiceDAO.deleteCommercialInovice( dbTransaction, customerShippingId );
				success = true;
				HashMap info = new HashMap();
				info.put ("PackingSlip (" + packingSlipForm.getLabel() + ") has been cancelled", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
			}
			catch (ScalarException se)
            {
				HashMap errors = new LinkedHashMap();
				errors.put ("Internal Server Error", "Could not cancel packingslip (" + packingSlipForm.getLabel() + ")");
				errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);

				session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not cancel packingslip (" + packingSlipForm.getLabel() + ")" );
				session.setAttribute( SessionKeys.ERROR_REPORT, se );
				request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
			}
			finally
			{
				// Rollback or Commit the Transaction
				if (success == true)
				{
					dbTransaction.commit();
				}
				else
				{
					dbTransaction.rollback();
				}
            }
            return (mapping.findForward ("packingSlipMenu"));
		}
        // CONFIRM THIS PACKING SLIP 
		if ("confirmPackingSlip".equalsIgnoreCase (action))
		{
			PackingSlipForm packingSlipForm = ( PackingSlipForm ) form;
			int customerShippingId          = packingSlipForm.getCustomerShippingId();
			int noOfBoxes                   = packingSlipForm.getNoOfBoxesAsInt();
			String shippedVia               = packingSlipForm.getShippedVia();
			String weight                   = packingSlipForm.getWeight();
			String grossWeight              = packingSlipForm.getGrossWeight();
			String contactPerson            = packingSlipForm.getContactPerson();
			String invoiceNo                = packingSlipForm.getInvNo();
			String shipDate                 = packingSlipForm.getShipDate();
			String[] tracking               =  packingSlipForm.getTracking();

            try
			{
				PackingSlipDAO.confirmPackingSlip( customerShippingId, noOfBoxes, tracking, currentUser, shippedVia, weight, contactPerson, invoiceNo, shipDate, grossWeight );
				HashMap info = new HashMap();
				info.put ("PackingSlip (" + packingSlipForm.getLabel() + ") has been confirmed", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
            }
            catch (ScalarException se)
			{
				HashMap errors = new LinkedHashMap();
				errors.put ("Internal Server Error", "Could not confirm packingslip (" + packingSlipForm.getLabel() + ")");
				errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);
                request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not confirm packingslip (" + packingSlipForm.getLabel() + ")" );
                session.setAttribute( SessionKeys.ERROR_REPORT, se );
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            return (mapping.findForward ("packingSlipMenu"));
        }
        
        // VIEW EXISTING PACKING SLIP
		if (("view".equalsIgnoreCase (action)) || ("viewShipped".equalsIgnoreCase (action)))
		{

			session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
			request.setAttribute ("showNoModifyMessage", "TRUE");
			session.removeAttribute("repetedPartNumber");
			session.removeAttribute("orgFinalInventoryDataList");
			int customerShippingId = -1;
			try
			{
				customerShippingId = Integer.parseInt ((String) request.getAttribute ("customerShippingId"));
			}
			catch (NumberFormatException nfe) {}

			if( ( String ) request.getAttribute("customerShippingId") == null )
            {
                try{ customerShippingId = Integer.parseInt ((String) request.getParameter ("customerShippingId")); } catch (NumberFormatException nfe) {}
            }
            int salesOrderId = -1;
            try
			{
				salesOrderId = Integer.parseInt ((String) request.getParameter ("salesOrderId"));
			}
			catch (NumberFormatException nfe) {}

            if ((customerShippingId != -1) && (customerShippingId != -2))
			{

				//System.out.println("Customer Shipping Id = " + customerShippingId);
				// create and save packingSlipForm
				boolean success = false;
				PackingSlipForm packingSlipForm = null;
				try
				{
					packingSlipForm = PackingSlipDAO.loadPackingSlipById (customerShippingId);
					if ( ( packingSlipForm.getNoOfBoxes()=="0" ) || ( packingSlipForm.getNoOfBoxes().equals("0") ) )
                    {
                        packingSlipForm.setNoOfBoxes("");
                    }
                    else
                    {
						if (request.getParameter("noOfBoxes") != null)
						{
							packingSlipForm.setNoOfBoxes(request.getParameter("noOfBoxes"));
						}
                    }
					if ( ( request.getParameter( "noOfBoxes" ) != null ) && ( request.getParameterValues( "tracking" ) != null ) )
					{
						packingSlipForm.setNoOfBoxes( request.getParameter( "noOfBoxes" ) );
						String[] trackingNumbers = request.getParameterValues( "tracking" );
						if( ( trackingNumbers != null ) && ( trackingNumbers.length == 1 ) && ( trackingNumbers[0] != null ) && ( trackingNumbers[0].indexOf( ';' ) != -1 ) )
						{
							packingSlipForm.setTracking( StringUtils.toStringArray( trackingNumbers[0], ";" ) );
						}
						else
						{
							packingSlipForm.setTracking( trackingNumbers );
						}
					}
                    if( request.getParameter( "shippedVia" ) != null )
					{
						packingSlipForm.setShippedVia( request.getParameter( "shippedVia" ) );
                    }
                    if( request.getParameter( "shipDate" ) != null)
					{
                        packingSlipForm.setShipDate( request.getParameter( "shipDate" ) );
                    }
                    if( request.getParameter( "weight" ) != null)
					{
						try
						{
							packingSlipForm.setWeight( request.getParameter( "weight" ) );
						}
						catch(Exception ex){}
                    }
                    if( request.getParameter( "invNo" ) != null)
					{
						packingSlipForm.setInvNo( request.getParameter( "invNo" ) );
                    }
                    if( request.getParameter( "contactPerson" ) != null)
					{
						packingSlipForm.setContactPerson( request.getParameter( "contactPerson" ) );
                    }
                    success = true;
                }
                catch (ScalarException se)
				{
					HashMap errors = new LinkedHashMap();
					errors.put ("Internal Server Error", "Could not load Packing Slip");
					errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);
                    request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
                    session.setAttribute( SessionKeys.ERROR_REPORT, se );
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
				}

                if (success == true)
				{
					request.setAttribute ("packingSlipForm", packingSlipForm);
					// add salesOrderId list to the session
					if (session.getAttribute("salesOrderIdList") == null)
					{
						ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
						session.setAttribute ("salesOrderIdList", ids);
					}
                    // save lineItems
                    HashMap customerShippingLineItemMap = packingSlipForm.getLineItemMap();
                    request.setAttribute ("customerShippingLineItemMap", customerShippingLineItemMap);
                    session.setAttribute ("csLineItemMap", customerShippingLineItemMap);

                    // Load all packingslips generated for this sales order
                    ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (packingSlipForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
                    request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

                    // Create and save OrderLineItems
                    // If "1" is passed as parameter all the line items with HOLD status also will appear
                    HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (packingSlipForm.getSalesOrderId(), 1 );
                    ArrayList orderLineItemList = new ArrayList();

                    // Keep Line Items that are
                    java.util.Set setCsltKey = customerShippingLineItemMap.keySet();
                    Object[] arrayCsltKey =  setCsltKey.toArray();
                    java.util.Arrays.sort(arrayCsltKey);
                    int length = arrayCsltKey.length;
                    Object lineItemIdKey = null;
                    for(int count=0; count < length; count++ )
					{
						lineItemIdKey = arrayCsltKey[count];
                        if (orderLineItemMap.containsKey (lineItemIdKey) == true)
						{
                            orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                        }

					}

    				// To facilitate the Board and kit Parent  child partnumbers
					// repeting part numbers
					ArrayList repetedPartNumber = new ArrayList();
					repetedPartNumber = PackingSlipDAO.getRepetedPartNumbers ( orderLineItemList );

					if( repetedPartNumber.size() > 0 )
					{
						session.setAttribute("repetedPartNumber",repetedPartNumber);
					}

                    request.setAttribute ("orderLineItemList", orderLineItemList);
                    request.setAttribute ("action", "viewPackingSlip");
                    if("viewShipped".equalsIgnoreCase (action))
					{
                        return (mapping.findForward ("updateForInv"));
                    }
					else
					{
                        return (mapping.findForward (returnVal));
                    }
                }
                else
				{
                    // Failed to load packing slip by id
                    // Goto New packing slip screen
                    action = "newPackingSlip";
                }
            }
            else if (salesOrderId != -1)
			{
                action = "loadSalesOrder";
            }
            else
			{
                if (customerShippingId == -2)  // Confirm the packingslip automatically after saving it.
				{
                    request.setAttribute ("AUTO_CONFIRM_PACKING_SLIP", "true");
                }
                action = "newPackingSlip";  // goto newPackingSlip screen
            }
        }

        // LOAD SALES ORDER INFORMATION
        if ("loadSalesOrder".equalsIgnoreCase(action))
		{
			session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
			session.removeAttribute( "repetedPartNumber" );
			session.removeAttribute( "orgFinalInventoryDataList" );
            try
			{
                String salesOrderId = request.getParameter ("salesOrderId");

                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder (salesOrderId);
                int total = PackingSlipDAO.getTotalNumberOfPackingSlipsGenerated (salesOrderId);
                Customer customer = CustomerDAO.loadCustomerById (salesOrder.getCustomerId());

				String shippingContactPerson = PackingSlipDAO.getShippingOrBillingContactPerson ( null, salesOrderId );
                String shippedVia = "";

                if ( ( salesOrder.getShippingMethod() != null ) && ( salesOrder.getShippingMethod().trim().length() != 0 ) ) {
                   shippedVia = salesOrder.getShippingMethod().trim();
                } else{
                   shippedVia = "";
                }
                // -- END --
               // Create PackingSlipForm for the given salesOrderId and save it in request
               PackingSlipForm packingSlipForm = new PackingSlipForm (
                                                  "PS-" + salesOrder.getSalesOrderNo() + "-" + (total + 1), //+ "-" + (long)(Math.random()*10000000), //packing slip label
                                                  -1,   //customerShippingId
                                                  salesOrder.getSalesOrderId(),
                                                  salesOrder.getSalesOrderNo(),
                                                  salesOrder.getCustomerName(),
                                                  salesOrder.getCustomerPO(),
                                                  shippingContactPerson, //Bhaskar modified on 29 Jan 2004
                                                  customer.getRepOffice(),
                                                  customer.getTerms(),
                                                  salesOrder.getDeliveryTerms(), //fob
                                                  null,   //noOfBoxes
                                                  null, //tracking
                                                  shippedVia,
                                                  salesOrder.getShippingMethod(),
                                                  salesOrder.getShippingAccount(),
                                                  salesOrder.getBillingAddress(),
                                                  salesOrder.getShippingAddress(),
                                                  salesOrder.getShippingInstructions());

                packingSlipForm.setInvNo( PackingSlipDAO.getNextPsInvoiceNumber(null));
                packingSlipForm.setShippingToAddressId (salesOrder.getShippingAddressId());
                packingSlipForm.setShipDate (StringUtils.formatDateToString (new Date(System.currentTimeMillis())));
                request.setAttribute("packingSlipForm", packingSlipForm);

                // add salesOrderId list to the session
                if (session.getAttribute("salesOrderIdList") == null) {
                    ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
                    session.setAttribute ("salesOrderIdList", ids);
                }

                // Load all packingslips generated for this sales order
                ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (Integer.parseInt(salesOrderId), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
                request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

                // Get CustomerShippingLineItems for this salesOrderId
                HashMap customerShippingLineItemMap = PackingSlipDAO.loadShippableLineItemMapBySalesOrderId (Integer.parseInt(salesOrderId));
                request.setAttribute ("customerShippingLineItemMap", customerShippingLineItemMap);

                // Create OrderLineItems and save it in request
                // passing "0" as parameter retrives only APPROVED status line items
                HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (Integer.parseInt (salesOrderId), 0 );
                if(orderLineItemMap.isEmpty() == true)
				{
                    //Put the errors message if there are no approved lineItems
                    HashMap m_errors = new HashMap();
                    m_errors.put ("No Approved LineItems left in this SalesOrder", null);
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
                }
				// This is added Separately because the Customer Part Number must be added only for new packing Slips
				PackingSlipDAO.loadCustomerPartNumber( customerShippingLineItemMap, orderLineItemMap, salesOrder.getCustomerId() );

                ArrayList orderLineItemList = new ArrayList();
                java.util.Set setCsltKey = customerShippingLineItemMap.keySet();
                Object[] arrayCsltKey =  setCsltKey.toArray();
                java.util.Arrays.sort(arrayCsltKey);
                int length = arrayCsltKey.length;
                Object lineItemIdKey = null;
                for(int count=0; count < length; count++ )
				{
                    lineItemIdKey = arrayCsltKey[count];
                    if (orderLineItemMap.containsKey (lineItemIdKey) == true)
					{
                        orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                    }
                }
                request.setAttribute ("orderLineItemList", orderLineItemList);
				ArrayList repetedPartNumber = new ArrayList();
				repetedPartNumber = PackingSlipDAO.getRepetedPartNumbers ( orderLineItemList );
				if( repetedPartNumber.size() > 0 )
				{
					session.setAttribute("repetedPartNumber",repetedPartNumber);
				}
                returnVal = "success";
            }
            catch (ScalarException se)
			{
                HashMap m_errors = new HashMap();
                if (se.getRootCause().getMessage().indexOf ("No Line Items are pending") != -1)
				{
                    m_errors.put ("Sales order ID", "There are no pending line items to be shipped. Please select another Sales Order ID");
                }
                else
				{
                    m_errors.put ("Sales order ID", "Unable to load this sales order ID data <br>Please select another Sales Order ID");
                }
                request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
                m_errors = new HashMap();   // reset the errors hash-map
            }
			if (returnVal.equalsIgnoreCase("success"))
			{
				return (mapping.findForward (returnVal));
			}
            request.removeAttribute("packingSlipForm");
            action = "newPackingSlip";
        }

        // SAVE THE PACKING SLIP INFORMATION INTO DATABASE AND GENERATE PACKING SLIP
        if ("save".equalsIgnoreCase (action))
		{
            HashMap lineItemMap = null;
            HashMap finalInventoryMap = null;
            PackingSlipForm packingSlipForm = (PackingSlipForm) form;
            m_errors = validateForm (packingSlipForm, true);

            // Valid form
            if ((m_errors == null) || (m_errors.isEmpty() == true))
			{
                try
				{
					// CHECK IF THERE ARE ANY ERRORS IN FINAL INVENTORY POP-UP WINDOW
					HashMap finalInventoryActionErrors = (HashMap) session.getAttribute ("FINAL_INVENTORY_ACTION_ERRORS");
					session.removeAttribute ("FINAL_INVENTORY_ACTION_ERRORS");

					if ((finalInventoryActionErrors != null) && (finalInventoryActionErrors.isEmpty() == false))
					{
						m_errors.putAll (finalInventoryActionErrors);
					}
					else
					{
                        int fromLocationId = -1;
                        try
						{
							fromLocationId = Integer.parseInt ((String) session.getAttribute (SessionKeys.SHIPPING_FROM_LOCATION_ID));
                        }
						catch (NumberFormatException nfe) {}
                        session.removeAttribute (SessionKeys.SHIPPING_FROM_LOCATION_ID);

                        if (fromLocationId == -1)
						{
							//m_errors.put ("Couldnt save Packing Slip, Invalid values entered in Quantity Pull window", null);
                        }
                        else
						{
							packingSlipForm.setShippingFromLocationId (fromLocationId);
							lineItemMap = getLineItemsFromRequest (request);
                            if( ( m_errors.isEmpty() ) && ( ( lineItemMap != null ) && ( lineItemMap.isEmpty() == false ) ) )
                            {
                                finalInventoryMap = (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP);
                                if (finalInventoryMap == null)
								{
                                    m_errors.put ("Couldnt save Packing Slip, Invalid values entered in Quantity Pull window", null);
                                }
                                else
								{
                                    boolean confirmPackingSlip = false;
                                    if ("true".equalsIgnoreCase (request.getParameter ("autoConfirmPackingSlip")))
									{
										confirmPackingSlip = true;
                                    }
                                    int customerShippingId = PackingSlipDAO.saveCustomerShippingInfo (packingSlipForm, Arrays.asList(lineItemMap.values().toArray()), finalInventoryMap, currentUser, confirmPackingSlip);
                                    session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
									session.removeAttribute("repetedPartNumber");//remove the attribute that was set when the PS has two line items with same part number

                                    packingSlipForm.setCustomerShippingId (customerShippingId);
                                    request.setAttribute ("SAVE_PACKING_SLIP", "yes");
                                    returnVal = "packingSlipView";
                                }
                            }
                            if ((m_errors.isEmpty()) && ((lineItemMap == null) || (lineItemMap.isEmpty() == true)))
							{
                                m_errors.put ("No line items", "Please select at least one Line Item");
                            }
                        }
                    }
                }
                catch (ScalarException se)
				{
                    se.getRootCause().printStackTrace();
                    m_errors.put ("Couldnot save the packing slip", null);
                }
            }
            // Load all packingslips generated for this sales order
            ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (packingSlipForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
            request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

            // Get CustomerShippingLineItems for this salesOrderId
            if (returnVal.equalsIgnoreCase("packingSlipView") != true)
			{
				lineItemMap = PackingSlipDAO.loadShippableLineItemMapBySalesOrderId (packingSlipForm.getSalesOrderId());
            }
            request.setAttribute ("customerShippingLineItemMap", lineItemMap); 

            // Create OrderLineItems and save it in request
            HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (packingSlipForm.getSalesOrderId(), 0);
            ArrayList orderLineItemList = new ArrayList();

            java.util.Set lineItemKey = lineItemMap.keySet();
            Object[] arrayLineTemKey =  lineItemKey.toArray();
            java.util.Arrays.sort(arrayLineTemKey);
            int length = arrayLineTemKey.length;
            Object lineItemIdKey = null;
            for(int count=0; count < length; count++ )
			{
                lineItemIdKey = arrayLineTemKey[count];
                if (orderLineItemMap.containsKey (lineItemIdKey) == true)
				{
					orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                }
            }
			// added by ravikanth on 20 Aug 2003 for sorting by PO Line Item
             if (returnVal.equalsIgnoreCase("packingSlipView"))
			 {
				 Collections.sort(orderLineItemList,new PackingSlipComparator());
             }

            request.setAttribute ("orderLineItemList", orderLineItemList);

            if (m_errors.isEmpty() == false)
			{
				request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
				m_errors = new HashMap();
            }

            ClientInfo clientInfo = new ClientInfo();
            clientInfo = UserDAO.getClientAddressInfo();

            request.setAttribute("clientAddress",clientInfo);


            request.setAttribute ("showMainMenu", "true");
            return (mapping.findForward (returnVal));
        }

        // UPDATE EXISTING PACKING SLIP
        if ("updatePackingSlip".equalsIgnoreCase (action))
		{
            HashMap lineItemMap = null;
            HashMap finalInventoryMap = null;
            PackingSlipForm packingSlipForm = (PackingSlipForm) form;
            m_errors = validateForm (packingSlipForm, false);
            // Valid form
            if ((m_errors == null) || (m_errors.isEmpty() == true))
			{
                try
				{
					lineItemMap = getLineItemsFromRequest (request);
                    if ((m_errors.isEmpty()) && ((lineItemMap != null) && (lineItemMap.isEmpty() == false)))
					{
                        finalInventoryMap = (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP);
                        PackingSlipDAO.updateCustomerShippingInfo (packingSlipForm, Arrays.asList(lineItemMap.values().toArray()), finalInventoryMap, currentUser);
                        session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
                        request.setAttribute ("UPDATE_PACKING_SLIP", "yes");
                        returnVal = "packingSlipView";
                    }
                }
                catch (ScalarException se)
				{
                    se.getRootCause().printStackTrace();
                    m_errors.put ("Couldnot save the packing slip", null);
                }
            }

            // Load all packingslips generated for this sales order
            ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (packingSlipForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
            request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

            // Show line items
            if (returnVal.equalsIgnoreCase("packingSlipView") != true)
			{
                lineItemMap = (HashMap) session.getAttribute ("csLineItemMap");
                if (lineItemMap == null) lineItemMap = new HashMap();
            	    session.removeAttribute ("csLineItemMap");
            }

            request.setAttribute ("customerShippingLineItemMap", lineItemMap);

            // Create and save OrderLineItems
            HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (packingSlipForm.getSalesOrderId(),1);
            if (orderLineItemMap == null) orderLineItemMap = new HashMap();

            ArrayList orderLineItemList = new ArrayList();

            // added by hareesh on 9th July 2003
            java.util.Set lineItemKey = lineItemMap.keySet();
            Object[] arrayLineTemKey =  lineItemKey.toArray();
            java.util.Arrays.sort(arrayLineTemKey);
            int length = arrayLineTemKey.length;
            Object lineItemIdKey = null;
            for(int count=0; count < length; count++ )
			{
                lineItemIdKey = arrayLineTemKey[count];
                if (orderLineItemMap.containsKey (lineItemIdKey) == true)
				{
                    orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                }
            } 
            Collections.sort(orderLineItemList,new PackingSlipComparator());
            request.setAttribute ("orderLineItemList", orderLineItemList);

            if (m_errors.isEmpty() == false)
			{
                request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
                m_errors = new HashMap();
                request.setAttribute ("action", "viewPackingSlip");
            }

			session.removeAttribute("repetedPartNumber");
			session.removeAttribute("orgFinalInventoryDataList");

            ClientInfo clientInfo = new ClientInfo();
            clientInfo = UserDAO.getClientAddressInfo();

            request.setAttribute("clientAddress",clientInfo);


            request.setAttribute ("showMainMenu", "true");
            return (mapping.findForward (returnVal));
        }

        //UPDATE PACKING SLIP FOR ONLY INV NO AND AIRWAY BILL NO
        if("updateInvNoAndAirwayBillNo".equalsIgnoreCase(action))
		{
            PackingSlipForm packingSlipForm = (PackingSlipForm) form;
            PackingSlipDAO.updateCustomerShippingForInvNo( packingSlipForm, currentUser );
            HashMap errors = new HashMap();
            errors.put("Packing Slip Details", "Saved Successfully");
            if(!errors.isEmpty())
                request.setAttribute(SessionKeys.INFO_MESSAGES, errors);

            request.setAttribute ("showMainMenu", "true");
            return (mapping.findForward ("packingSlipMenu"));
        }

        // PACKING SLIP - PRINTABLE FORMAT 
        if ("printView".equalsIgnoreCase (action))
		{
            request.setAttribute ("confirmPackingSlip", request.getParameter("confirmPackingSlip"));
            request.setAttribute ("cancelPackingSlip", request.getParameter("cancelPackingSlip"));
            request.setAttribute ("showMainMenu", request.getParameter("showMainMenu"));
            request.setAttribute ("showNoModifyMessage", "FALSE");

            int customerShippingId = -1;
            try
			{
                customerShippingId = Integer.parseInt ((String) request.getParameter ("customerShippingId"));
            }
            catch (NumberFormatException nfe)
			{
                // Invalid or no value
            }

            if (customerShippingId != -1)
			{
                // create and save packingSlipForm
                boolean success = false;
                PackingSlipForm packingSlipForm = null;
                try
				{
                    packingSlipForm = PackingSlipDAO.loadPackingSlipById (customerShippingId);
                    if ( ( packingSlipForm.getNoOfBoxes()=="0" ) || ( packingSlipForm.getNoOfBoxes().equals("0") ) )
                    {
                        packingSlipForm.setNoOfBoxes("");
                    }
                    success = true;
                }
                catch (ScalarException se)
				{
                    HashMap errors = new LinkedHashMap();
                    errors.put ("Internal Server Error", "Could not load Packing Slip");
                    errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);
                    // Balaram, on July 8, 2003
                    request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
                    session.setAttribute( SessionKeys.ERROR_REPORT, se );
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                }

                if (success == true)
				{
                    request.setAttribute ("packingSlipForm", packingSlipForm);
                    // add salesOrderId list to the session
                    if (session.getAttribute("salesOrderIdList") == null)
					{
                        ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
                        session.setAttribute ("salesOrderIdList", ids);
                    }

                    // save lineItems
                    HashMap customerShippingLineItemMap = packingSlipForm.getLineItemMap();
                    request.setAttribute ("customerShippingLineItemMap", customerShippingLineItemMap);

                    // Create and save OrderLineItems
                    HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (packingSlipForm.getSalesOrderId(), 1);
                    ArrayList orderLineItemList = new ArrayList();

                     // added by hareesh on 9th July 2003
                    java.util.Set setCsltKey = customerShippingLineItemMap.keySet();
                    Object[] arrayCsltKey =  setCsltKey.toArray();
                    java.util.Arrays.sort(arrayCsltKey);
                    int length = arrayCsltKey.length;
                    Object lineItemIdKey = null;
                    for(int count=0; count < length; count++ )
					{
                        lineItemIdKey = arrayCsltKey[count];
                        if (orderLineItemMap.containsKey (lineItemIdKey) == true)
						{
                            orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                        }
                    } 
					Collections.sort(orderLineItemList,new PackingSlipComparator());
                    request.setAttribute ("orderLineItemList", orderLineItemList);
                }
            }
            ClientInfo clientInfo = new ClientInfo();
            clientInfo = UserDAO.getClientAddressInfo();

            request.setAttribute("clientAddress",clientInfo);

            return (mapping.findForward ("packingSlipView"));
        }
        // OPEN NEW PACKING SLIP 
        if ("newPackingSlip".equalsIgnoreCase(action))
		{
            try
			{
                if (session.getAttribute("salesOrderIdList") == null)
				{
                    ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
                    session.setAttribute ("salesOrderIdList", ids);
                }

                returnVal = "success";
            }
            catch (ScalarException se)
			{
                se.getRootCause().printStackTrace();
            }
        }

        return (mapping.findForward ("success"));
    }

	private HashMap getLineItemsFromRequest (HttpServletRequest request)
    {

        HashMap lineItems = new HashMap();

        int lineItemCount = Integer.parseInt (request.getParameter ("lineItemCount"));

        int lineItemId = -1;
        int lineItemNumber = -1;
        int quantityShipped = 0;
        int quantityRequested = 0;
        int previousQuantityShipped = 0;
        int pendingQuantity = 0;
        String description = null;
		String softwareVersion = null;
        String units = null;
        String customerPartNumber = null;

        CustomerShippingLineItem lineItem = null;
        for (int i=0; i<lineItemCount; i++) {

            String selected = request.getParameter ("select_" + i);

            if (selected == null) {
                continue;
            }

            try {
                lineItemId = Integer.parseInt (request.getParameter ("lineItemId_"+i));
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Line Item ID", "Invalid Line Item ID.. " + request.getParameter ("lineItemId_"+i));
            }

            try {
                lineItemNumber = Integer.parseInt (request.getParameter ("lineItemNumber_"+i));
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Line Item Number", "Invalid Line Item Number.. " + request.getParameter ("lineItemNumber_"+i));
            }


            try {
                quantityRequested = Integer.parseInt (request.getParameter ("quantityRequested_"+i));
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Requested Quantity", "Invalid value for Requested Quantity.. " + request.getParameter ("quantityRequested_"+i));
            }

            try {
                previousQuantityShipped = Integer.parseInt (request.getParameter ("previousQuantityShipped_"+i));
            }
            catch (NumberFormatException nfe) {
                //no value
            }

            try {
            	//System.out.println("Quantity Shipped  "+ request.getParameter ("quantityShipped_"+i));
                quantityShipped = Integer.parseInt (request.getParameter ("quantityShipped_"+i));

                if (quantityShipped <= 0) {
                    m_errors.put ("Quantity Shipped (Line Item: " + lineItemNumber + ")", "-ve value is entered for Quantity Shipped.. " + quantityShipped);
                }

                pendingQuantity = (quantityRequested - (quantityShipped - previousQuantityShipped));

                if (pendingQuantity < 0) {
                    m_errors.put ("Quantity Shipped (Line Item: " + lineItemNumber + ")", "Cannot ship more quantity than requested.");
                }
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Quantity Shipped (Line Item: " + lineItemNumber + ")", "Invalid value entered for Quantity Shipped.. " + request.getParameter ("quantityShipped_"+i));
            }
                description = request.getParameter ("description_"+i);
                units = request.getParameter ("units_"+i);
				customerPartNumber = request.getParameter("customerPartNumber_"+i);

            if (m_errors.isEmpty() == false) {
                continue;
            }

            int csLineItemId = -1;
            try {
                csLineItemId = Integer.parseInt (request.getParameter ("id_" + i));
            }
            catch (NumberFormatException nfe) { }

            String shippedDate = request.getParameter ("shippedDate_" + i);
            lineItem = new CustomerShippingLineItem (lineItemId, quantityShipped, pendingQuantity, shippedDate,description,softwareVersion);
            lineItem.setId (csLineItemId);
			lineItem.setCustomerPartNumber(customerPartNumber);
			lineItem.setLineItemNumber( lineItemNumber );
			lineItem.setUnits(units);

            lineItems.put (lineItemId + "", lineItem);
        }


        return lineItems;
    }


    private HashMap validateForm (PackingSlipForm packingSlipForm, boolean checkLabel) throws ScalarException {

        HashMap errors = new HashMap();

        if (packingSlipForm == null) {
            errors.put ("Internal Server Error occured while processing the request", null);

            return errors;
        }

        if (checkLabel == true) {
            String label = packingSlipForm.getLabel();
            if ((label == null) || (label.trim().length() == 0)) {
                errors.put ("Label", "Packingslip Label is invalid");
            }
            else if (PackingSlipDAO.doesPackingSlipLabelExist (label) == true) {
                errors.put ("Label", "Packing Slip Label, " + label + " already exists");
            }
        }

        try {
            String noOfBoxes = packingSlipForm.getNoOfBoxes();
            if ((noOfBoxes != null) && (noOfBoxes.trim().length() != 0)) {
                Integer.parseInt (packingSlipForm.getNoOfBoxes());
            }
        }
        catch (NumberFormatException nfe) {
            errors.put ("No Of Boxes", "Not a number, please enter a valid number");
        }

        String shipDate = packingSlipForm.getShipDate();
        if ((shipDate == null) || (shipDate.trim().length() == 0)) {
            errors.put ("Ship Date", "Please enter a valid Ship Date");
        }


        return errors;
    }


    public String formatAsHTML (String host, PackingSlipForm packingSlipForm, ArrayList orderLineItemList, HashMap csLineItemMap, HashMap finalInventoryMap) {

        StringBuffer buf = new StringBuffer (2098);
		String MFG_PART_NUMBER_KEY = "";
		String CUSTOMER_PART_NUMBER_KEY = "";


		try
		{
			 MFG_PART_NUMBER_KEY = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mktgPartNumber");
		}
		catch ( NullPointerException e )
		{
			 MFG_PART_NUMBER_KEY = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
		}
		try
		{
			 CUSTOMER_PART_NUMBER_KEY = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.customerPartNumber");
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_PART_NUMBER_KEY = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
		}
		//Changed by hareesh on 29th August 2003
        // -- START --
        String backgroundImage = "";
        if (Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase (packingSlipForm.getStatus())) {
            backgroundImage = "http://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/cancelled_icon.gif";
        }
        // -- END --

        //--------------------------------------------------------
        /* chakravarthy  - 3-03-2004: get the client address information from the userdao
         * using the method getClientAddressInfo()
         * display each of address fileds in html view of packing slip below
         * using clientInfo object
         */
        ClientInfo clientInfo = new ClientInfo();
        try{
              clientInfo = UserDAO.getClientAddressInfo();
        }catch (ScalarException slex){}

        clientInfo.getAddress();

        //--------------------------------------------------------

        buf.append ("<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>\n");
        buf.append ("<link href='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/stylesheets/scalarsoft.css' type='text/css' rel='stylesheet'>\n");
        buf.append ("</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>\n");
        //buf.append ("<TABLE cellSpacing=0 cellPadding=0 width='70%' border='0' >\n");
        //buf.append ("<TR><td width='180' valign='top' background='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/left_red_bg.gif'>\n");
        //buf.append ("<TD bgcolor='#ffffff'><IMG height=9 src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' width=8></TD>\n");
        //buf.append ("<TD bgcolor='#ffffff'><IMG height=480 src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' width=2></TD>\n");
        //buf.append ("<TD valign='top' width='100%'><IMG height=1 src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/clear.gif' width=500 border=0><BR>\n");
        buf.append ("<!-- body starts -->\n");

        //buf.append ("<img src='http://" + host + "/" +ConfigManager.getChipTracContext() +"/jsp/includes/images/scalar_logo.jpg' width=180 height=72 border=0>\n");
        //buf.append ("<center><span class='NArialW'><h2>Packing Slip</h2></span></center>\n");
        //buf.append ("<BR>\n");

        //buf.append ("<table border='0' width='90%' align='center'  background=''>\n");
        buf.append ("<table border='0' width='90%' align='center'  background='"+backgroundImage+"'>\n"); //Changed by hareesh on 29th August 2003
        //buf.append ("<td width='21%'><font class='NArialL'>PackingSlip Label: </font></td>\n");
        buf.append ("<tr><td align='center'>");
        buf.append ("<table width='100%' border='0' class='NArialR' bordercolor='#000000' cellspacing='0'>");
            buf.append ("<TR><td width='35%' align='center'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/scalar_logo.jpg' height='120' width='200' border='0' ></td>");
            //buf.append ("<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'></td>");
            //buf.append ("<td width='35%' align='center' class='NArialL'><font class='NArialW'>Packing Slip</font><br>" +  ConfigManager.getClientAddressLine1());
            buf.append ("<td width='35%' align='center' class='NArialL'><font class='NArialW'>Packing Slip</font><br>" + clientInfo.getClientName() );
            //buf.append ("<br>"+ ConfigManager.getClientAddressLine2() + "<br>" + ConfigManager.getClientAddressLine3() + "<br>" + ConfigManager.getClientPhone() + "<br>" + ConfigManager.getClientFax() + "</td>\n");

   		    buf.append ("<br>");
            // check address1 for null and and append the address1
			buf.append ( ( ( clientInfo.getAddress().getAddress1()  == null )   || ( clientInfo.getAddress().getAddress1().trim().length() == 0) )		? "" : clientInfo.getAddress().getAddress1() );

            // if address1 and address2 are not null then append " , and blankspace" to the address1 (above)
			if( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) && ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) )
			{
				buf.append (",&nbsp;");
			}

            // check address2 for null and append the address2
			buf.append ( (( clientInfo.getAddress().getAddress2()  == null )   || ( clientInfo.getAddress().getAddress2().trim().length() == 0) )		? "" : clientInfo.getAddress().getAddress2() );

            // if address1 and address2 are not null then append  -- " brake <br>" to the address line
			if( ( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) ) )
			{
				buf.append ("<br>");
			}

            // check city for null and append the city
			buf.append ( ( ( clientInfo.getAddress().getCity() == null ) || ( clientInfo.getAddress().getCity().trim().length() == 0)     )	   ? "" : clientInfo.getAddress().getCity() );

            // if city and state both are not null then append  -- " , and blank space " to the city
			if( ( clientInfo.getAddress().getCity() != null ) && ( clientInfo.getAddress().getCity().trim().length() > 0 ) )
			{
				if ( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
				{
					buf.append (",&nbsp;"); //append to the city
				}
			}

            // check state for null and append the state
			buf.append ( ( ( clientInfo.getAddress().getState() == null )       || ( clientInfo.getAddress().getState().trim().length() == 0 ) )        ? "" : clientInfo.getAddress().getState() );

            // if state and zipcode both are not null then append  -- " , and blank space " to the state
			if( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) && ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
			{
				buf.append (",&nbsp;");// append to teh state
			}

            // check zipcode for null and append the zipcode
            buf.append ( ( ( clientInfo.getAddress().getZipCode() == null )     || ( clientInfo.getAddress().getZipCode().trim().length() == 0 ) )      ? "" : clientInfo.getAddress().getZipCode() );

            // check phone number & fax number for null and append the phone number and fax number with brakes(<br>)
			buf.append ( (( clientInfo.getAddress().getPhoneNumber() == null ) || ( clientInfo.getAddress().getPhoneNumber().trim().length() == 0 ) )  ? "" : "<br>Ph: "  +  clientInfo.getAddress().getPhoneNumber()  );
            buf.append ( (( clientInfo.getAddress().getFaxNumber() == null )   || ( clientInfo.getAddress().getFaxNumber().trim().length() == 0 ) )    ? "" : "<br>Fax: " +  clientInfo.getAddress().getFaxNumber()    );

            buf.append ("</td>\n");

            buf.append ("<td width='30%'>&nbsp;</td></TR>");
        buf.append ("</table></td></tr>");
        //buf.append ("<tr><td width='40%' align='center'>\n");
        //buf.append ("<td width='30%' colspan='2'>&nbsp;</td>");
        //buf.append ("<td width='15%'>&nbsp;</td></tr>");
         buf.append ("<tr><td align='center'>");
        buf.append ("<table width='100%' border='0' class='NArialRS' bordercolor='#000000' cellspacing='0'>");
        buf.append ("<tr><td bgcolor='#FFFFEE' class='NArialRS' width='40%' align='left'>");
        buf.append ("<table width='100%' class='NArialRS' border='1' bordercolor='#000000' cellspacing='0'>");
        buf.append ("<tr height='30'><td class='NArialR' bgcolor='#DEE1E2' >Ship From:</td></tr>");

        //Shipping Address
        buf.append ("<tr><td class='NArialRS' >" + clientInfo.getClientName());
        buf.append ("<br>");
        // check address1 for null and and append the address1
        buf.append ( ( ( clientInfo.getAddress().getAddress1()  == null )   || ( clientInfo.getAddress().getAddress1().trim().length() == 0) )		? "" : clientInfo.getAddress().getAddress1() );

        // if address1 and address2 are not null then append " , and blankspace" to the address1 (above)
        if( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) && ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) )
        {
            buf.append (",&nbsp;");
        }

        // check address2 for null and append the address2
        buf.append ( (( clientInfo.getAddress().getAddress2()  == null )   || ( clientInfo.getAddress().getAddress2().trim().length() == 0) )		? "" : clientInfo.getAddress().getAddress2() );

        // if address1 and address2 are not null then append  -- " brake <br>" to the address line
        if( ( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) ) )
        {
            buf.append ("<br>");
        }

        // check city for null and append the city
        buf.append ( ( ( clientInfo.getAddress().getCity() == null ) || ( clientInfo.getAddress().getCity().trim().length() == 0)     )	   ? "" : clientInfo.getAddress().getCity() );

        // if city and state both are not null then append  -- " , and blank space " to the city
        if( ( clientInfo.getAddress().getCity() != null ) && ( clientInfo.getAddress().getCity().trim().length() > 0 ) )
        {
            if ( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
            {
                buf.append (",&nbsp;"); //append to the city
            }
        }

        // check state for null and append the state
        buf.append ( ( ( clientInfo.getAddress().getState() == null )       || ( clientInfo.getAddress().getState().trim().length() == 0 ) )        ? "" : clientInfo.getAddress().getState() );

        // if state and zipcode both are not null then append  -- " , and blank space " to the state
        if( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) && ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
        {
            buf.append (",&nbsp;");// append to teh state
        }

        // check zipcode for null and append the zipcode
        buf.append ( ( ( clientInfo.getAddress().getZipCode() == null )     || ( clientInfo.getAddress().getZipCode().trim().length() == 0 ) )      ? "" : clientInfo.getAddress().getZipCode() );

        // check phone number & fax number for null and append the phone number and fax number with brakes(<br>)
        buf.append ( (( clientInfo.getAddress().getPhoneNumber() == null ) || ( clientInfo.getAddress().getPhoneNumber().trim().length() == 0 ) )  ? "" : "<br>Ph: "  +  clientInfo.getAddress().getPhoneNumber()  );
        buf.append ( (( clientInfo.getAddress().getFaxNumber() == null )   || ( clientInfo.getAddress().getFaxNumber().trim().length() == 0 ) )    ? "" : "<br>Fax: " +  clientInfo.getAddress().getFaxNumber()    );

        buf.append("</td></tr></table></td>");
        //End of Shipping Address

/*            buf.append ("<tr><td class='NArialRS' >" + ConfigManager.getClientAddressLine1() + "<br>" + ConfigManager.getClientAddressLine2() + "<br>" + ConfigManager.getClientAddressLine3() + "<br><br>");
            buf.append ("<br>" + ConfigManager.getClientPhone() + "<br>" + ConfigManager.getClientFax() + " </td></tr></table></td>");
*/
            buf.append ("<td width='20%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'></td>");
            buf.append ("<td  width='40%' bgcolor='#FFFFEE' class='NArialRS' align='right'>");
            buf.append ("<table width='100%' class='NArialRS' border='1' bordercolor='#000000' cellspacing='0'>");
            buf.append ("<tr height='30'><td class='NArialR' bgcolor='#DEE1E2' >Ship To:</td></tr>");
            buf.append ("<tr><td><font class='NArialRS'>" + ((packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName()) + "</font><BR>");
			//Bhaskar added this code block on 29 Jan 2004
			String contactPerson = "";
			try
			{
				contactPerson = packingSlipForm.getContactPerson();
				if ( ( contactPerson == null ) || ( ( contactPerson != null ) && ( contactPerson.equalsIgnoreCase ( "null" ) ) ) )
				{
					contactPerson = "";
				}
				else
				{
					contactPerson = packingSlipForm.getContactPerson();
				}
			}
			catch(Exception e)
			{
				contactPerson = "";
			}
            buf.append ("<font class='NArialRS'>" + (contactPerson.trim().length() == 0 ? "&nbsp;" : contactPerson+"," ) + "</font><BR>");
            buf.append ("<font class='NArialRS'>");
            try
            {
                Address shippingAddress = packingSlipForm.getShippingAddressObject();
                if (shippingAddress == null)
                {
                    shippingAddress = UserDAO.loadAddressById (packingSlipForm.getShippingToAddressId());
                }
                // changed by hareesh on 5th July 2003
                // -- START --
                // Removed the &nbsp; when city or state or country is null
                //System.out.println(" shippingAddress.getAddress1(): "+ shippingAddress.getAddress1());
                buf.append ( (( (shippingAddress.getAddress1() == null) || (shippingAddress.getAddress1().trim().length() == 0) ) ? "" : shippingAddress.getAddress1()+"<BR>") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getAddress2() == null) || (shippingAddress.getAddress2().trim().length() == 0) ) ? "" : shippingAddress.getAddress2()+"<BR>") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getCity() == null) || (shippingAddress.getCity().trim().length() == 0) ) ? "" : shippingAddress.getCity()+",") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getState() == null) || (shippingAddress.getState().trim().length() == 0) ) ? "" : shippingAddress.getState()+",") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getCountry() == null) || (shippingAddress.getCountry().trim().length() == 0) ) ? "" : shippingAddress.getCountry()+"&nbsp;") );
                //buf.append("&nbsp;");
                // -- END --
                buf.append ( (( (shippingAddress.getZipCode() == null) || (shippingAddress.getZipCode().trim().length() == 0) ) ? "" : shippingAddress.getZipCode()) );
                buf.append("<BR><BR> Ph. ");
                buf.append ( (( (shippingAddress.getPhoneNumber() == null) || (shippingAddress.getPhoneNumber().trim().length() == 0) ) ? "" : shippingAddress.getPhoneNumber()) );
                buf.append("<BR> Fax. ");
                buf.append ( (( (shippingAddress.getFaxNumber() == null) || (shippingAddress.getFaxNumber().trim().length() == 0) ) ? "" : shippingAddress.getFaxNumber()) );

            }
            catch (Exception e)
            {
                System.out.println(" Exception in formatAsHtml: " +e);
            }
            //buf.append ("<font class='NArialL'>" + ((packingSlipForm.getShippingAddress() == null) ? "" : packingSlipForm.getShippingAddress()) + "</font>");
            buf.append ("</font></table></td></tr>");
        buf.append ("</table></td></tr>");

        buf.append ("<tr><td width='100%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='20'></td></tr>");
        /**
        buf.append ("<tr><td width='21%'><font class='NArialL'>PackingSlip Label:</font></td>");
        buf.append ("<td width='21%'><font class='NArialL'><font class='NArialL'>" + ((packingSlipForm.getLabel() == null) ? "" : packingSlipForm.getLabel()) + "</font></td>");
        buf.append ("<td width='3%'>&nbsp;</td><td width='21%'>&nbsp;</td><td width='21%'>&nbsp;</td><td width='3%'>&nbsp;</td></tr>");
        buf.append ("<tr><td width='21%'><font class='NArialL'>Customer PO:</font></td>
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getCustomerPO() == null) ? "" : packingSlipForm.getCustomerPO()) + "</font></td>");
        buf.append ("<td width="3%">&nbsp;</td> <td width="21%"><font class="NArialL">Customer Name:</font></td>
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td></tr>");
        buf.append ("<tr><td width='21%'><font class='NArialL'>Shipping Contact Person:</font></td>");
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getContactPerson() == null) ? "" : packingSlipForm.getContactPerson()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td><td width='21%'><font class='NArialL'>Rep Office:</font></td>");
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getRepOffice() == null) ? "" : packingSlipForm.getRepOffice()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td></tr>");

        buf.append ("<tr><td width='21%'><font class='NArialL'>Terms</font></td>\n");
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getTerms() == null) ? "" : packingSlipForm.getTerms()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>FOB</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getFob() == null) ? "" : packingSlipForm.getFob()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
        buf.append ("</tr>\n");

        buf.append ("<tr>\n");
            buf.append ("<td width='21%'><font class='NArialL'>No. Of Boxes</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getNoOfBoxes() == null) ? "" : packingSlipForm.getNoOfBoxes()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");

            buf.append ("<td width='21%'><font class='NArialL'>Tracking</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getTracking() == null) ? "" : packingSlipForm.getTracking()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
       buf.append ("</tr>\n");

       buf.append ("<tr>\n");
            buf.append ("<td width='21%'><font class='NArialL'>Shipped VIA:</font></td>");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.shippedVia() == null) ? "" : packingSlipForm.shippedVia()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
       buf.append ("</tr>\n");

        buf.append ("<tr>\n");
            buf.append ("<td width='21%'><font class='NArialL'>Billing Address</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getBillingAddress() == null) ? "" : packingSlipForm.getBillingAddress()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");

            buf.append ("<td width='21%'><font class='NArialL'>Shipping Address :</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getShippingAddress() == null) ? "" : packingSlipForm.getShippingAddress()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
        buf.append ("</tr>\n");
        **/

        buf.append ("<tr><td width='100%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10'></td></tr>");
         buf.append ("<tr><td width='100%'>\n");
         buf.append ("<table border='1' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>\n");
         buf.append ("<TR>\n");
                    buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Customer PO#</td>\n");
                    buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Sales Order#</td>\n");
                    buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>PackingSlip Label</td>\n");  //chakravarthy : added packingslip label
                    buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Actual Ship Date</td>\n");
                    buf.append ("<td width='20%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Shipped Via</td>\n");
                    buf.append ("<td width='28%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Del. Terms</td>");
                    buf.append ("<td width='4%'   class='NArialR' align='center' bgcolor='#DEE1E2'># Cartons</td>");
                    buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Weight (Lbs)</td>");
                buf.append ("</tr>");
                buf.append ("<tr>");
                    buf.append ("<td width='12%' align='center' bgcolor='#FFFFEE'>"+((packingSlipForm.getCustomerPO() == null) ? "&nbsp;" : packingSlipForm.getCustomerPO())+"</td>");
                    buf.append ("<td width='12%' align='center' bgcolor='#FFFFEE'>"+((packingSlipForm.getSalesOrderNumber() == null) ? "&nbsp;" : packingSlipForm.getSalesOrderNumber())+"</td>");
                    buf.append ("<td width='12%' align='center' bgcolor='#FFFFEE'>"+((packingSlipForm.getLabel() == null) ? "&nbsp;" : packingSlipForm.getLabel())+"</td>");                        //chakravarthy: added packingslip label
                    buf.append ("<td width='12%' align='center'  bgcolor='#FFFFEE'>" + ((packingSlipForm.getShipDate() == null) ? "&nbsp;" : packingSlipForm.getShipDate())+"</td>");
                    buf.append ("<td width='20%' align='center' bgcolor='#FFFFEE'>" + ((packingSlipForm.getShippedVia() == null) ? "&nbsp;" : packingSlipForm.getShippedVia())+"&nbsp;</td>");
                    // changed by hareesh on 5th July 2003
                    // -- START --
                    //buf.append ("<td width='28%' align='center' bgcolor='#FFFFEE'>" + ((packingSlipForm.getTerms() == null) ? "&nbsp;" : packingSlipForm.getTerms())+"</td>");
                    buf.append ("<td width='28%' align='center' bgcolor='#FFFFEE'>" + ((packingSlipForm.getFob() == null) ? "&nbsp;" : packingSlipForm.getFob())+"</td>");
                    // -- END --
                    buf.append ("<td width='4%' align='right'  bgcolor='#FFFFEE'>" + ( ((packingSlipForm.getNoOfBoxes() == null) || (packingSlipForm.getNoOfBoxes().equals("0")))? "&nbsp;" : packingSlipForm.getNoOfBoxes())+"</td>");
					String weight = "";
					try
					{
						if ( packingSlipForm.getWeight().trim().length() > 0 )
						{
							weight = StringUtils.formatAmount((float)(new Double(packingSlipForm.getWeight().trim()).doubleValue()), "$###,###.##");
						}
						else
						{
							weight = "&nbsp;";
						}
					}
					catch (Exception e)
					{
						weight = "&nbsp;";
					}
                    buf.append ("<td width='12%' align='right' bgcolor='#FFFFEE'>" + weight +"</td>");
                buf.append ("</tr></table></td></tr>");

        buf.append ("<tr><td  width='100%'><font class='NArialR'><strong><u>Shipping Instructions:</u></strong></font></td></tr>\n");

        buf.append ("<tr><td  bgcolor='#DEE1E2'><font class='NArialRS'>" + ((packingSlipForm.getShippingInstructions() == null) ? "" : packingSlipForm.getShippingInstructions()) + "</font></td></tr>\n");

        buf.append ("<tr><td ><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10' ></td></tr>\n");
     buf.append ("<tr><td  width='100%' >\n");
            buf.append ("<table border='0' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>\n");

        buf.append ("<tr><td  width='100%' >\n");
            buf.append ("<table border='1' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>\n");


				 buf.append ("<tr>\n");
                    buf.append ("<td width='5%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>PO Line<br> Item</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>"+ MFG_PART_NUMBER_KEY+"</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>"+ CUSTOMER_PART_NUMBER_KEY+" </font></td>");//Bhaskar on 17 December 2003
                    buf.append ("<td width='25%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Description</font></td>");

                    buf.append ("<td width='5%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Unit Type</font></td>");
                    buf.append ("<td width='9%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Request Date</font></td>");
                    buf.append ("<td width='9%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Schedule Date</font></td>");
                    buf.append ("<td width='6%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Req Qty</font></td>");
                    buf.append ("<td width='6%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Qty Shipped</font></td>");
                    buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2' nowrap><font class='NArialR'>Lot # Vs Qty</font></td>");
                buf.append ("</tr>\n");

                    //buf.append ("<td width='5%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Line Item</td>");
                    //buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Marketing Part No</td>");
                    //buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Mfg Part No</td>");
                    //buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Software Version</td>");
                    //buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Qty Shipped</td>");
                    //buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>UoM</td>");
                    //buf.append ("<td width='25%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Description</td>");
                    //buf.append ("<td width='20%' nowrap align='center' bgcolor='#DEE1E2' nowrap><font class='NArialL'>Lot Number Vs Qty</td>");
                //buf.append ("</tr>\n");

            /**
                buf.append ("<tr>\n");
                    buf.append ("<td width='4%'  align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Line Item</font></td>\n");
                    buf.append ("<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Marketing Part No</font></td>\n");
                    buf.append ("<td width='25%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Description</font></td>\n");
                    buf.append ("<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Manufacturing Part No</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Req. Ship Date</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Sch. Ship Date</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Requested Quantity</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Quantity To be Shipped</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Quantity Shipped</font></td>\n");
                    buf.append ("<td width='8%'  align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Lot Numbers</font></td>\n");
                buf.append ("</tr>\n");
                **/


        if (orderLineItemList == null) orderLineItemList = new ArrayList();
        if (csLineItemMap == null) csLineItemMap = new HashMap();
        if (finalInventoryMap == null) finalInventoryMap = new HashMap();

	// added by ravikanth on 20 Aug 2003 for sorting by PO Line Item
		Collections.sort(orderLineItemList,new PackingSlipComparator());

        LineItem lineItem = null;
        CustomerShippingLineItem csLineItem = null;
        ArrayList finalInventoryList = null;
        FinalInventoryData finalInventoryData = null;
        int finalInventoryListSize = -1;
        int size = orderLineItemList.size();

		HashMap customerShippingLotNumberMap = null;
		Iterator customerShippingLotNumbers = null;
		CustomerShippingLotNumberData customerShippingLotNumberData = null;

        for (int i=0; i<size; i++) {
            lineItem = (LineItem) orderLineItemList.get (i);
            csLineItem = (CustomerShippingLineItem) csLineItemMap.get (lineItem.getLineItemId()+"");
            finalInventoryList = (ArrayList) finalInventoryMap.get (lineItem.getLineItemId()+"");
            String description = ( ( ( csLineItem.getDescription() == null ) || ( csLineItem.getDescription().trim().length() == 0 ) ) ? lineItem.getDescription() : csLineItem.getDescription());
            String customerPartNumber = ( ( ( csLineItem.getCustomerPartNumber() == null ) || ( csLineItem.getCustomerPartNumber().trim().length() == 0 ) ) ? "&nbsp;" : csLineItem.getCustomerPartNumber() );//Changed by hareesh on 24th Decemeber 2003
			//System.out.println ("formatAsHTML method in PSA : "+csLineItem.getCustomerPartNumber());
			String version = (csLineItem.getSoftwareVersion() == null ? "" :csLineItem.getSoftwareVersion());
			String units = csLineItem.getUnits();//Bhaskar on 24 Jan 2004
			if((units == null) || ((units != null) && (units.equalsIgnoreCase("null"))))
			units = "";

                buf.append ("<tr>\n");
                    buf.append ("<td width='5%'  align='center' bgcolor='#FFFFEE'><font class='NArialRS'>");
                    	if( lineItem.getPoLineItemNo() == 0 )
                    	{
							buf.append ("&nbsp;");
                    	}
					  	else
					  	{
							buf.append (lineItem.getPoLineItemNo());
					  	}
					buf.append ("</font></td>\n");
                    buf.append ("<td width='10%' nowrap align='left' bgcolor='#FFFFEE'><font class='NArialRS'>" + /*lineItem.getMarketingPartNo()*/ lineItem.getManufacturingPartNo() + "</font></td>\n");
					buf.append ("<td width='10%' nowrap align='left' bgcolor='#FFFFEE'><font class='NArialRS'>" + customerPartNumber + "</font></td>\n");
                    buf.append ("<td width='25%' align='left' bgcolor='#FFFFEE'>");
                    buf.append ("<table border='0' width='100' bgcolor='#FFFFEE' class='viewTable'><tr><td align='left' bgcolor='#FFFFEE'><font class='NArialRS'>");
                    buf.append ( ( ( ( description == null ) || ( description.trim().length() == 0 ) ) ? "" : description ) +"</font></td></tr></table></td>");

                    buf.append ("<td width='5%' align='left' bgcolor='#FFFFEE'><font class='NArialRS'>" + ( ( units.trim().length() == 0 )  ? "&nbsp;" : units ) + "</font></td>\n");
                    buf.append ("<td width='9%' align='center' bgcolor='#FFFFEE'><font class='NArialRS'>" + (lineItem.getRequestDate()!=null?lineItem.getRequestDate():"&nbsp;") + "&nbsp;</font></td>\n");
                    buf.append ("<td width='9%' align='center' bgcolor='#FFFFEE'><font class='NArialRS'>" + (lineItem.getScheduleDate()!=null?lineItem.getScheduleDate():"&nbsp;") + "&nbsp;</font></td>\n");
                    buf.append ("<td width='6%' align='right' bgcolor='#FFFFEE'><font class='NArialRS'>" + StringUtils.formatUnits ( lineItem.getQuantity() ) + "</font></td>\n");
                    buf.append ("<td width='6%' align='right' bgcolor='#FFFFEE'><font class='NArialRS'>");

                    if (csLineItem != null) buf.append ( StringUtils.formatUnits ( csLineItem.getQtyShipped() ) );
                    buf.append ("</font></td>\n");

		            buf.append ("<td width='15%' align='center' bgcolor='#FFFFEE' nowrap><font class='NArialR'>\n");
                    buf.append ("<table bgcolor='#FFFFEE' border='1' bordercolor='#000000' cellspacing='0'  cellpadding='0' width='100%' >\n");

                   	String lotNumbers = "";

					try {
                    	customerShippingLotNumberMap = PackingSlipDAO.loadCustomerShippingLotNumberData (packingSlipForm.getCustomerShippingId(), lineItem.getLineItemId());
					}
					catch (ScalarException se) {
						System.out.println ("Exception while load customer shipping lot number data from database");
						se.printStackTrace();
					}

					if (customerShippingLotNumberMap == null) customerShippingLotNumberMap = new HashMap();

					customerShippingLotNumbers = customerShippingLotNumberMap.values().iterator();

					int qtyPull = 0;
					while (customerShippingLotNumbers.hasNext()) {
						customerShippingLotNumberData = (CustomerShippingLotNumberData) customerShippingLotNumbers.next();
						qtyPull = customerShippingLotNumberData.getQtyPull();

						if (qtyPull > 0) {

							buf.append ("<tr>");
							buf.append ("<td nowrap align='left'><font class='NArialRS'>" + customerShippingLotNumberData.getLotNumber() + "</font></td>");
							buf.append ("<td nowrap align='right'><font class='NArialRS'>" + qtyPull + "</font></td>");
							buf.append ("</tr>");
						}
					}

                    buf.append ("</table></font></td>\n");

					/*
                        String lotNumbers = "";
                        if (finalInventoryList == null) {
                            try {
                                finalInventoryList = FinalInventoryDAO.loadFinalInventoryData (lineItem.getMarketingPartNo());
                            }
                            catch (ScalarException se) {
                                // Couldnt load FinalInventoryData List from databse... ignore
                            }
                        }

                        if (finalInventoryList != null) {
                            finalInventoryListSize = finalInventoryList.size();

                            for (int j=0; j<finalInventoryListSize; j++) {
                                finalInventoryData = (FinalInventoryData) finalInventoryList.get (j);

                                if (finalInventoryData != null) {
                                    lotNumbers += finalInventoryData.getLotNumber() + "<br>";
                                }
                            }
                        }

                buf.append ("<td width='8%' align='center' bgcolor='#DEE1E2'><font class='NArialL'><%=lotNumbers%></font></td>\n");
                */
            buf.append ("</tr>\n");

        }   // for (int i=0; i<size; i++)

            //buf.append ("<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='60' ></td></tr>\n");
               // buf.append ("<tr><td colspan=9><BR></td></tr>\n");
	   buf.append ("</table></td></tr>\n");

        buf.append ("<tr><td ><BR></td></tr>\n");
		/*
		This block is added by Bhaskar on 26 Jan 2004 begin
		*/
        buf.append ("<tr><td colspan=4>");
		buf.append("<table border='0' width='100%' align='center' bordercolor='#FFFFFF' cellspacing='2' cellpadding='2'>");
		buf.append("<tr><td align='center'><font class='NArialView'>CERTIFICATE OF COMPLIANCE</font></td></tr>");
		buf.append("<tr><td><font class='NArialRS'>THIS PRODUCT SHIPPED HERE WITH HAVE BEEN INSPECTED AND COMPLY WITH THE "+
		"REQUIREMENTS OF YOUR PURCHASE ORDER TO THE EXTENT THAT SUCH REQUIREMENT HAVE BEEN ACCEPTED AND ACKNOWLEDGED BY "+
		"CAVIUM SUBSTANTIATING INSPECTION AND TEST ON THAT FILE.</font></td></tr>");
		buf.append ("<tr><td align='center'><font class='NArialRS'><B>THANK YOU FOR YOUR BUSINESS!</B></font></td></tr></table>");
        buf.append ("</td></tr>\n");
		/*
		This block is added by Bhaskar on 26 Jan 2004 ends
		*/

        buf.append ("<tr><td ><BR></td></tr>\n");

        //buf.append ("<tr>\n");
          //  buf.append ("<td bgcolor='silver' colspan=3 class='NArialL' valign='top' align='top'>Customer Note:</td>\n");
           // buf.append ("<td>&nbsp;</td>\n");
            //buf.append ("<td bgcolor='silver' colspan=2 class='NArialL' valign='top' align='top'>Received By:</td>\n");
        //buf.append ("</tr>\n");
        buf.append ("<tr><td width='100%'><table width='100%'>\n");
        buf.append ("<tr>\n");
            buf.append ("<td class='NArialR' width='35%'><b>Packer:</b> </td>\n");
            buf.append ("<td class='NArialR' width='35%'>__________________________________________</td>");
            buf.append ("<td width='30%'>&nbsp;</td>");
        buf.append ("</tr>\n");
        buf.append ("</table></td></tr>\n");
        buf.append ("<tr><td width='100%'><table width='100%'>\n");

        buf.append ("<tr>\n");
            buf.append ("<td class='NArialR' width='35%'><b>Hand Carry Receipt</b>\n");
            buf.append ("<td class='NArialR' width='35%'>__________________________________________<br> <b>Signature & Title</b>");
            buf.append ("<td width='30%'>&nbsp;</td>");

        buf.append ("</table></td></tr>\n");
        buf.append ("<tr><td width='100%'><table width='100%'>\n");

        buf.append ("<tr>\n");
            buf.append ("<td class='NArialR' width='35%'>&nbsp;\n");
            buf.append ("<td class='NArialR' width='35%'>__________________________________________<br> <b>Print Name & Date</b> ");
            buf.append ("<td width='30%'>&nbsp;</td>\n");
        buf.append ("</tr>\n");
        buf.append ("</table></td></tr>\n");

        buf.append ("</table>\n");

        buf.append ("<!-- till here -->\n");

       // buf.append ("</TD></TR>\n");
        //buf.append ("</TABLE>\n");

        buf.append ("</body>\n");

        buf.append ("</html>\n");


        return buf.toString();
    }


    /**
     *@return creates a temporary PackingSlip HTML form, and returns the absolute path
     */
    public String getPackingSlipAsHtmlFile( String host, PackingSlipForm packingSlipForm, ArrayList orderLineItemList, HashMap csLineItemMap, HashMap finalInventoryMap)
    {
        String filePath = null;
        String psAsHtml = formatAsHTML(host, packingSlipForm, orderLineItemList, csLineItemMap, finalInventoryMap);

        if( psAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try {
            // CREATE TEMPORARY ATTACHMENT FILE
            //File tempDir = new File ("chiptrac_temp_dir").getCanonicalFile();
            String mailingTempDir = ConfigManager.getMailerTempDir();
            File tempDir = new File (mailingTempDir).getCanonicalFile();
            tempDir.mkdir();

            // Packing Slip Attachment File Name - Start    -- Balaram, July 1, 2003
            String psAttachmentFileName = packingSlipForm.getLabel();
            if( ( psAttachmentFileName != null ) && ( psAttachmentFileName.startsWith( "PS-" ) ) )
            {
                // Changed by hareesh on 27th August 2003
                //psAttachmentFileName = "Packing_Slip_SO#" + psAttachmentFileName.substring( 3 );
                psAttachmentFileName = psAttachmentFileName.substring( 3 );
            }

            // Changed by hareesh on 27th August 2003
            //psAttachmentFileName = psAttachmentFileName + ".html";
            //psAttachmentFileName = "Packing_Slip_SO#" + psAttachmentFileName + ".html";
            psAttachmentFileName = "Packing_Slip_SO_" + psAttachmentFileName + ".html";
            // Packing Slip Attachment File Name - END -- Balaram, July 1, 2003

            psAttachment = new File( tempDir.getCanonicalPath(), psAttachmentFileName );
            psAttachment.deleteOnExit();

            if( ( psAttachment.exists() == true ) || ( psAttachment.createNewFile() == true ) )
            {
                fWriter = new FileWriter (psAttachment, false);

                fWriter.write( psAsHtml );

                fWriter.close();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath();
            }
        }
        catch( Exception e )
        {
            System.out.println( "Exception while creating packingslip html file");
            e.printStackTrace();
        }
        finally
        {
            if( fWriter != null )
            {
                try
                {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ){}
            }
        }

        return filePath;
    }
    // changed by hareesh on 2nd February 2004
    // CDATA is set for every xml element.
    // added by hareesh on 23th Decemeber 2003
    public String formatAsXML (String host, PackingSlipForm packingSlipForm, ArrayList orderLineItemList, HashMap csLineItemMap, HashMap finalInventoryMap) {

        StringBuffer buf = new StringBuffer (2098);

        //--------------------------------------------------------
        /* chakravarthy 3-03-2004: get the client address information from the userdao
         * using the method getClientAddressInfo()
         * display each of address fileds in pdf view of packing slip below
         * using clientInfo object
         */
        ClientInfo clientInfo = new ClientInfo();
        try{
              clientInfo = UserDAO.getClientAddressInfo();
        }catch (ScalarException slex){}

        clientInfo.getAddress();

        //--------------------------------------------------------


        buf.append ( "<?xml version='1.0' encoding='UTF-8'?>\n" );

        if (Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase (packingSlipForm.getStatus())) {
            buf.append ( "<packingSlip cancel='1'> \n" );
        } else {
            buf.append ( "<packingSlip cancel='0'> \n" );
        }
        String imagesDirLocation = ConfigManager.getChipTracImagesDir();
        String scalarLogo = ConfigManager.getScalarLogo();
        String crossCancel = ConfigManager.getCrossCanelImage();
		//Bhaskar added this code block on 29 Jan 2004
		String contactPerson = "";
		try
		{
			contactPerson = packingSlipForm.getContactPerson();
			if ( ( contactPerson == null ) || ( ( contactPerson != null ) && ( contactPerson.equalsIgnoreCase ( "null" ) ) ) )
			{
				contactPerson = "";
			}
			else
			{
				contactPerson = packingSlipForm.getContactPerson();
			}
		}
		catch(Exception e)
		{
			contactPerson = "";
		}

		buf.append ("<images>\n");
        buf.append ( "<logo>"+imagesDirLocation + scalarLogo +"</logo> \n" );
        buf.append ("<cancelImage>"+imagesDirLocation+crossCancel+"</cancelImage> \n ");
        buf.append ("</images>\n");
        buf.append ( "<selfAddress> \n" );

        //buf.append ( "<name><![CDATA[" ) .append( ConfigManager.getClientAddressLine1() ) .append( "]]></name> \n" );
        //buf.append ( "<address1><![CDATA[" ) .append( ConfigManager.getClientAddressLine2() ) .append( "]]></address1> \n" );
        //buf.append ( "<address2><![CDATA[" ) .append( ConfigManager.getClientAddressLine3() ) .append( "]]></address2> \n" );
        //buf.append ( "<address3><![CDATA[]]></address3> \n " );
        //buf.append ( "<phone><![CDATA[" ) .append ( ConfigManager.getClientPhone() ) .append ( "]]></phone> \n" );
        //buf.append ( "<fax><![CDATA[" ) .append ( ConfigManager.getClientFax() ) .append ( "]]></fax> \n" );
        //buf.append ( "</selfAddress> \n" );

        //-------------------------------------------
        //chakravarthy
        buf.append ( "<name><![CDATA[" );
        buf.append ( clientInfo.getClientName() );
        buf.append ( "]]></name> \n" );
        buf.append ( "<address1><![CDATA[" );
        buf.append ( ( clientInfo.getAddress().getAddress1()  == null )   || ( clientInfo.getAddress().getAddress1().trim().length() == 0)     ? "" : clientInfo.getAddress().getAddress1()  );

        // if address1 and address2 are not null then append " , and blankspace" to the address1 (above)
        if( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) && ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) )
        {
            buf.append (", ");
        }

        buf.append ( ( clientInfo.getAddress().getAddress2()  == null )   || ( clientInfo.getAddress().getAddress2().trim().length() == 0)     ? "" : clientInfo.getAddress().getAddress2() );

/*
		// if address1 and address2 are not null then append  -- " brake <br>" to the address line
        if( ( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) ) )
        {
            buf.append ("");
        }
*/
        buf.append ( "]]></address1> \n" );


        buf.append ( "<address2><![CDATA[" );
        buf.append ( ( clientInfo.getAddress().getCity() == null )        || ( clientInfo.getAddress().getCity().trim().length() == 0)         ? "" : clientInfo.getAddress().getCity()   );

        // if city and state both are not null then append  -- " , and blank space " to the city
        if( ( clientInfo.getAddress().getCity() != null ) && ( clientInfo.getAddress().getCity().trim().length() > 0 ) )
        {
            if ( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
            {
                buf.append (", "); //append to the city
            }
        }


        buf.append ( ( clientInfo.getAddress().getState() == null )       || ( clientInfo.getAddress().getState().trim().length() == 0 )       ? "" : clientInfo.getAddress().getState()   );

        // if state and zipcode both are not null then append  -- " , and blank space " to the state
        if( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) && ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
        {
            buf.append (", ");// append to the state
        }

        buf.append ( ( clientInfo.getAddress().getZipCode() == null )     || ( clientInfo.getAddress().getZipCode().trim().length() == 0 )     ? "" : clientInfo.getAddress().getZipCode()  );
        buf.append ( "]]></address2> \n" );
        buf.append ( "<address3><![CDATA[]]></address3> \n " );
        buf.append ( "<phone><![CDATA[" );
        buf.append ( (clientInfo.getAddress().getPhoneNumber() == null )  || ( clientInfo.getAddress().getPhoneNumber().trim().length() == 0 ) ? "" : "Ph: " + clientInfo.getAddress().getPhoneNumber() );
        buf.append ( "]]></phone> \n" );
        buf.append ( "<fax><![CDATA[" );
        buf.append ( (( clientInfo.getAddress().getFaxNumber() == null )   || ( clientInfo.getAddress().getFaxNumber().trim().length() == 0 )) ? "" : "Fax: " +  clientInfo.getAddress().getFaxNumber() );
        buf.append ( "]]></fax> \n" );
        buf.append ( "</selfAddress> \n" );


/*
        buf.append ( (( clientInfo.getAddress().getAddress1()  == null )   || ( clientInfo.getAddress().getAddress1().trim().length() == 0) )    ? "" : clientInfo.getAddress().getAddress1()    + ",&nbsp;" );
        buf.append ( (( clientInfo.getAddress().getAddress2()  == null )   || ( clientInfo.getAddress().getAddress2().trim().length() == 0) )    ? "" : clientInfo.getAddress().getAddress2()    + "<br>"    );
        buf.append ( (( clientInfo.getAddress().getCity() == null )        || ( clientInfo.getAddress().getCity().trim().length() == 0) )        ? "" : clientInfo.getAddress().getCity()        + ",&nbsp;" );
        buf.append ( (( clientInfo.getAddress().getState() == null )       || ( clientInfo.getAddress().getState().trim().length() == 0 ) )      ? "" : clientInfo.getAddress().getState()       + ",&nbsp;" );
        buf.append ( (( clientInfo.getAddress().getZipCode() == null )     || ( clientInfo.getAddress().getZipCode().trim().length() == 0 )      ? "" : clientInfo.getAddress().getZipCode()     + "<br>" ));
        buf.append ( (( clientInfo.getAddress().getPhoneNumber() == null ) || ( clientInfo.getAddress().getPhoneNumber().trim().length() == 0 )) ? "" : clientInfo.getAddress().getPhoneNumber() + "Ph: ");
        buf.append ( (( clientInfo.getAddress().getFaxNumber() == null )   || ( clientInfo.getAddress().getFaxNumber().trim().length() == 0 ))   ? "" : clientInfo.getAddress().getFaxNumber()   + "Fax: " );
*/
        //-------------------------------------------
        // ShippingFromAddress
        buf.append ( "<shipFromAddress> \n");

        buf.append ( "<name><![CDATA[" );
        buf.append ( clientInfo.getClientName() );
        buf.append( "]]></name> \n" );
        buf.append ( "<address1><![CDATA[" );
        buf.append ( ( clientInfo.getAddress().getAddress1()  == null )   || ( clientInfo.getAddress().getAddress1().trim().length() == 0)     ? "" : clientInfo.getAddress().getAddress1()  );

        // if address1 and address2 are not null then append " , and blankspace" to the address1 (above)
        if( ( clientInfo.getAddress().getAddress1() != null ) && ( clientInfo.getAddress().getAddress1().trim().length() > 0 ) && ( clientInfo.getAddress().getAddress2() != null ) && ( clientInfo.getAddress().getAddress2().trim().length() > 0 ) )
        {
            buf.append (", ");
        }

        buf.append ( ( clientInfo.getAddress().getAddress2()  == null )   || ( clientInfo.getAddress().getAddress2().trim().length() == 0)     ? "" : clientInfo.getAddress().getAddress2() );
        buf.append( "]]></address1> \n" );
        buf.append ( "<address2><![CDATA[" );
        buf.append ( ( clientInfo.getAddress().getCity() == null )        || ( clientInfo.getAddress().getCity().trim().length() == 0)         ? "" : clientInfo.getAddress().getCity()   );

        // if city and state both are not null then append  -- " , and blank space " to the city
        if( ( clientInfo.getAddress().getCity() != null ) && ( clientInfo.getAddress().getCity().trim().length() > 0 ) )
        {
            if ( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) || ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
            {
                buf.append (", "); //append to the city
            }
        }
        buf.append ( ( clientInfo.getAddress().getState() == null )       || ( clientInfo.getAddress().getState().trim().length() == 0 )       ? "" : clientInfo.getAddress().getState()   );

        // if state and zipcode both are not null then append  -- " , and blank space " to the state
        if( ( ( clientInfo.getAddress().getState() != null ) && ( clientInfo.getAddress().getState().trim().length() > 0 ) ) && ( ( clientInfo.getAddress().getZipCode() != null ) && ( clientInfo.getAddress().getZipCode().trim().length() > 0 ) ) )
        {
            buf.append (", ");// append to the state
        }

        buf.append ( ( clientInfo.getAddress().getZipCode() == null )     || ( clientInfo.getAddress().getZipCode().trim().length() == 0 )     ? "" : clientInfo.getAddress().getZipCode()  );
        buf .append( "]]></address2> \n" );

        buf .append ( "<address3><![CDATA[]]></address3> \n " );

        buf .append ( "<phone><![CDATA[" );
        buf .append ( (clientInfo.getAddress().getPhoneNumber() == null )  || ( clientInfo.getAddress().getPhoneNumber().trim().length() == 0 ) ? "" : "Ph: " + clientInfo.getAddress().getPhoneNumber() );
        buf .append ( "]]></phone> \n" );

        buf .append ( "<fax><![CDATA[" );
        buf .append ( (( clientInfo.getAddress().getFaxNumber() == null )   || ( clientInfo.getAddress().getFaxNumber().trim().length() == 0 )) ? "" : "Fax: " +  clientInfo.getAddress().getFaxNumber() );
        buf .append ( "]]></fax> \n" );

/*
        buf.append ( "<name><![CDATA[" ) .append( ConfigManager.getClientAddressLine1() ) .append( "]]></name> \n" );
        buf.append ( "<address1><![CDATA[" ) .append( ConfigManager.getClientAddressLine2() ) .append( "]]></address1> \n" );
        buf.append ( "<address2><![CDATA[" ) .append( ConfigManager.getClientAddressLine3() ) .append( "]]></address2> \n" );
        buf.append ( "<address3><![CDATA[]]></address3> \n " );
        buf.append ( "<phone><![CDATA[" ) .append ( ConfigManager.getClientPhone() ) .append ( "]]></phone> \n" );
        buf.append ( "<fax><![CDATA[" ) .append ( ConfigManager.getClientFax() ) .append ( "]]></fax> \n" );
*/

        buf.append ( "</shipFromAddress> \n" );
        //End of ShippingFromAddress

        buf.append ( "<shipToAddress> \n");
        buf.append ( "<name><![CDATA[" ) .append( (packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName() ) .append( "]]></name> \n" );
        buf.append ( "<contactPerson><![CDATA[" ) .append( (contactPerson.trim().length() == 0 ) ? "" : contactPerson+"," ) .append( " ]]></contactPerson> \n" );
        try
        {
            Address shippingAddress = packingSlipForm.getShippingAddressObject();
            if (shippingAddress == null)
            {
                    shippingAddress = UserDAO.loadAddressById (packingSlipForm.getShippingToAddressId());
            }

            buf.append ( "<address1><![CDATA[" );
            buf.append ( ( ( (shippingAddress.getAddress1() == null) || (shippingAddress.getAddress1().trim().length() == 0) ) ? "" : shippingAddress.getAddress1()) );
            buf.append ( "]]></address1> \n" );
            buf.append ( "<address2><![CDATA[" );
            buf.append ( ( ( (shippingAddress.getAddress2() == null) || (shippingAddress.getAddress2().trim().length() == 0) ) ? "" : shippingAddress.getAddress2()) );
            buf.append ( "]]></address2> \n" );
            buf.append ( "<address3><![CDATA[" );
            buf.append ( ( ( (shippingAddress.getCity() == null) || (shippingAddress.getCity().trim().length() == 0) ) ? "" : shippingAddress.getCity()+",") );
            buf.append ( ( ( (shippingAddress.getState() == null) || (shippingAddress.getState().trim().length() == 0) ) ? "" : shippingAddress.getState()+",") );
            buf.append ( ( ( (shippingAddress.getCountry() == null) || (shippingAddress.getCountry().trim().length() == 0) ) ? "" : shippingAddress.getCountry() ) );
            buf.append ( ( ( (shippingAddress.getZipCode() == null) || (shippingAddress.getZipCode().trim().length() == 0) ) ? "" : shippingAddress.getZipCode()) );
            buf.append ( "]]></address3> \n" );
            buf.append ( "<phone><![CDATA[" );
            buf.append ( ( ( (shippingAddress.getPhoneNumber() == null) || (shippingAddress.getPhoneNumber().trim().length() == 0) ) ? "" : shippingAddress.getPhoneNumber()) );
            buf.append ( "]]></phone> \n" );
            buf.append ( "<fax><![CDATA[");
            buf.append ( ( ( (shippingAddress.getFaxNumber() == null) || (shippingAddress.getFaxNumber().trim().length() == 0) ) ? "" : shippingAddress.getFaxNumber()) );
            buf.append ( "]]></fax> \n"  );

        }
        catch (Exception e)
        {
            buf.append ( "<address1/> \n" );
            buf.append ( "<address2/> \n" );
            buf.append ( "<address3/> \n" );
            buf.append ( "<phone/> \n" );
            buf.append ( "<fax/> \n" );
            System.out.println(" Exception in formatAsXML: " +e);
        }
        buf.append ( "</shipToAddress> \n" );

        buf.append ( "<information> \n" );
		buf.append ( "<customerPO><![CDATA[" ) .append ( (packingSlipForm.getCustomerPO() == null) ? "" : packingSlipForm.getCustomerPO() ) .append ( "]]></customerPO> \n" );
		buf.append ( "<salesOrder><![CDATA[" ) .append ( (packingSlipForm.getSalesOrderNumber() == null) ? "" : packingSlipForm.getSalesOrderNumber() ) .append ("]]></salesOrder> \n");
                buf.append ( "<packingSlipLabel><![CDATA[" ) .append ( (packingSlipForm.getLabel() == null) ? "" : packingSlipForm.getLabel() ) .append ("]]></packingSlipLabel> \n");          // chakravarthy : added for packing slip label
		buf.append ( "<actualShipDate><![CDATA[" ) .append( (packingSlipForm.getShipDate() == null) ? "" : packingSlipForm.getShipDate() ) . append ( "]]></actualShipDate> \n" );
		buf.append ( "<shippedVia><![CDATA[" ) .append ( (packingSlipForm.getShippedVia() == null) ? "" : packingSlipForm.getShippedVia() ) .append( "]]></shippedVia> \n" );
		buf.append ( "<delTerms><![CDATA[" ) .append ( (packingSlipForm.getFob() == null) ? "" : packingSlipForm.getFob() ) .append ( "]]></delTerms> \n" );
		buf.append ( "<cartons><![CDATA[" ) .append ( ( ( packingSlipForm.getNoOfBoxes() == null ) || ( packingSlipForm.getNoOfBoxes().equals("0") ) )? "" : packingSlipForm.getNoOfBoxes() ) .append ( "]]></cartons> \n" );
		String weight = "";
		try
		{
			if ( packingSlipForm.getWeight().trim().length() > 0 )
			{
				weight = StringUtils.formatAmount((float)(new Double(packingSlipForm.getWeight().trim()).doubleValue()), "$###,###.##");
			}
			else
			{
				weight = "";
			}
		}
		catch (Exception e)
		{
			weight = "";
		}

		buf.append ( "<weight><![CDATA[" ).append (  weight ) .append ( " ]]></weight> \n" );
	    buf.append ( "</information> \n" );

        buf.append ( "<ShippingInstructions><![CDATA[" );
        buf.append ( ( (packingSlipForm.getShippingInstructions() == null) ? "" : packingSlipForm.getShippingInstructions().trim() ));
        buf.append ( "]]></ShippingInstructions> \n" );

        buf.append ( "<lineItems> \n" );
        String mfgPartTitle = "";
        try
        {
			mfgPartTitle = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mfgPartNumber");
        }
        catch( NullPointerException e )
        {
        	mfgPartTitle = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }
        buf.append ( "<mfgPartTitle><![CDATA[");
        buf.append ( mfgPartTitle );
		buf.append ( "]]></mfgPartTitle> \n" );

        if (orderLineItemList == null) orderLineItemList = new ArrayList();
        if (csLineItemMap == null) csLineItemMap = new HashMap();
        if (finalInventoryMap == null) finalInventoryMap = new HashMap();

	    Collections.sort(orderLineItemList,new PackingSlipComparator());

        LineItem lineItem = null;
        CustomerShippingLineItem csLineItem = null;
        ArrayList finalInventoryList = null;
        FinalInventoryData finalInventoryData = null;
        int finalInventoryListSize = -1;
        int size = orderLineItemList.size();

		HashMap customerShippingLotNumberMap = null;
		Iterator customerShippingLotNumbers = null;
		CustomerShippingLotNumberData customerShippingLotNumberData = null;

        for (int i=0; i<size; i++) {
            lineItem = (LineItem) orderLineItemList.get (i);
            csLineItem = (CustomerShippingLineItem) csLineItemMap.get (lineItem.getLineItemId()+"");
            finalInventoryList = (ArrayList) finalInventoryMap.get (lineItem.getLineItemId()+"");
            String description = ( ( ( csLineItem.getDescription() == null ) || ( csLineItem.getDescription().trim().length() == 0 ) ) ? lineItem.getDescription() : csLineItem.getDescription());
            String customerPartNumber = ( ( ( csLineItem.getCustomerPartNumber() == null ) || ( csLineItem.getCustomerPartNumber().trim().length() == 0 ) ) ? "" : csLineItem.getCustomerPartNumber());
            String version = (csLineItem.getSoftwareVersion() == null ? "" :csLineItem.getSoftwareVersion());
            String units = (csLineItem.getUnits() == null ? "":csLineItem.getUnits());//Bhaskar added on 24 Jan 2004

            buf.append ( "<lineItem> \n" );
                buf.append ( "<poLineItem><![CDATA[" );
                if( lineItem.getPoLineItemNo() == 0 )
					buf.append ("");
			  	else
							buf.append (lineItem.getPoLineItemNo());
               buf.append ( "]]></poLineItem> \n" );
               buf.append ( "<mfgPartNumber><![CDATA[" ) .append ( lineItem.getManufacturingPartNo() ) . append( "]]></mfgPartNumber>\n" );
			   buf.append ( "<CustomerPartNumber><![CDATA[") .append ( customerPartNumber ) .append ("]]></CustomerPartNumber>\n");
               buf.append ( "<description><![CDATA[" );
               buf.append ( ( ( ( description == null ) || ( description.trim().length() == 0 ) ) ? "" : description.trim() ) );
               buf.append ( "]]></description>\n" );
               buf.append ( "<units><![CDATA[" ) .append ( ( ( units == null ) || ( units.trim().length() == 0 ) ) ? "" : units ) .append ( "]]></units>\n" );
               buf.append ( "<requestDate><![CDATA[" ) .append ( lineItem.getRequestDate() != null ? lineItem.getRequestDate() : "" ) .append ( "]]></requestDate>\n" );
               buf.append ( "<scheduleDate><![CDATA[" ) .append ( lineItem.getScheduleDate() != null ? lineItem.getScheduleDate() : "" ).append ( "]]></scheduleDate>\n" );
               buf.append ( "<reqQty><![CDATA[" ) .append ( StringUtils.formatUnits ( lineItem.getQuantity() ) + "]]></reqQty>\n");
               buf.append ( "<qtyShipped><![CDATA[" );
               if (csLineItem != null) buf.append ( StringUtils.formatUnits ( csLineItem.getQtyShipped() ) );
               buf.append ( " ]]></qtyShipped>\n" );
               buf.append ( "<pulledLots>\n" );
               String lotNumbers = "";

               try {
                   	customerShippingLotNumberMap = PackingSlipDAO.loadCustomerShippingLotNumberData (packingSlipForm.getCustomerShippingId(), lineItem.getLineItemId());
			   }
			   catch (ScalarException se) {
					System.out.println ("Exception while load customer shipping lot number data from database");
					se.printStackTrace();
			   }

			   if (customerShippingLotNumberMap == null) customerShippingLotNumberMap = new HashMap();

			   customerShippingLotNumbers = customerShippingLotNumberMap.values().iterator();

			    int qtyPull = 0;
				while (customerShippingLotNumbers.hasNext()) {
					customerShippingLotNumberData = (CustomerShippingLotNumberData) customerShippingLotNumbers.next();
					qtyPull = customerShippingLotNumberData.getQtyPull();

					if (qtyPull > 0) {

                        buf.append ( "<lot>\n" );
                        buf.append ( "<lotName><![CDATA[ ").append ( customerShippingLotNumberData.getLotNumber() ).append ( "]]></lotName>\n" );
                        buf.append ( "<qty><![CDATA[" ) .append ( qtyPull ).append( " ]]></qty>\n" );
                        buf.append ("</lot>\n");
                    }
				}
            buf.append ( "</pulledLots>\n" );
            buf.append ( "</lineItem>\n" );
        }   // for (int i=0; i<size; i++)


	    buf.append ( "</lineItems>\n" );
        buf.append ( "</packingSlip>\n" );
        return buf.toString();

    }



    // added by hareesh on 23th December 2003
    /**
     *@return creates a temporary PackingSlip XML and PDF, and returns the absolute path of the PDF file
     */
    public String getPackingSlipAsPDFFile( String host, PackingSlipForm packingSlipForm, ArrayList orderLineItemList, HashMap csLineItemMap, HashMap finalInventoryMap)
    {
        String fileXMLPath = null;
        String filePDFPath = null;
        String fileXSLTPath = null;
        String psAsXML = formatAsXML(host, packingSlipForm, orderLineItemList, csLineItemMap, finalInventoryMap);

        if( psAsXML == null )
        {
            return fileXMLPath;
        }

        FileWriter fWriter = null;
        File psPDFAttachment = null;
        File psXML = null;

        try {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir();
            File tempDir = new File (mailingTempDir).getCanonicalFile();
            tempDir.mkdir();

            String psAttachmentFileName = packingSlipForm.getLabel();
            if( ( psAttachmentFileName != null ) && ( psAttachmentFileName.startsWith( "PS-" ) ) )
            {
                psAttachmentFileName = psAttachmentFileName.substring( 3 );
            }

            String xmlFileName = "Packing_Slip_SO_" + psAttachmentFileName + ".xml";
            String psAttachmentPDFFileName = "Packing_Slip_SO_" + psAttachmentFileName + ".pdf";
            String  xsltFileName = ConfigManager.getPackingSlipXml2PdfXslFile();

            psXML = new File( tempDir.getCanonicalPath(), xmlFileName );
            psXML.deleteOnExit();

            psPDFAttachment = new File( tempDir.getCanonicalPath(), psAttachmentPDFFileName );
            psPDFAttachment.deleteOnExit();

            if( ( psXML.exists() == true ) || ( psXML.createNewFile() == true ) )
            {
                fWriter = new FileWriter ( psXML, false);
                fWriter.write ( psAsXML );
                fWriter.close();
                fWriter = null;

                fileXMLPath = psXML .getCanonicalPath() .toLowerCase();
                filePDFPath = psPDFAttachment .getCanonicalPath() .toLowerCase();

                //System.out.println ( "XML Path " + fileXMLPath );
                //System.out.println ( "xslt Path " + xsltFileName );
                //System.out.println ( "PDF Path  " + filePDFPath );
                boolean success = PDFGenerator.convertXML2PDF( fileXMLPath, xsltFileName, filePDFPath );

            }
        }
        catch( Exception e )
        {
            System.out.println( "Exception while creating packingslip PDF file");
            e.printStackTrace();
        }
        finally
        {
            if( fWriter != null )
            {
                try
                {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ){}
            }
        }

        return filePDFPath;
    }


    public void sendPackingSlipMail (String from, String to, String subject, String message, String packingSlipAsHTML, HttpServletRequest request) {

        FileWriter fWriter = null;
        File psAttachment = null;
        try {
            // CREATE TEMPORARY ATTACHMENT FILE
            File tempDir = new File ("packingslip_temp_dir").getCanonicalFile();
            tempDir.mkdir();

            psAttachment = new File (tempDir.getCanonicalPath(), "Packingslip" + System.currentTimeMillis() + ".html");
            psAttachment.deleteOnExit();

            if ((psAttachment.exists() == true) || (psAttachment.createNewFile() == true)) {
                fWriter = new FileWriter (psAttachment, false);
                fWriter.write (packingSlipAsHTML);
                fWriter.close();
                fWriter = null;

                // SEND MAIL
                Mailer.send (from, to, null/*cc*/, null/*bcc*/, subject, message, new String[]{psAttachment.getAbsolutePath()}, Mailer.CONTENT_TYPE_HTML, false /*send mail to all email*/);
                //System.out.println ("Packing Slip information has been sent to " + to);
            }
        }
        catch (Exception e) {
            System.out.println ("Could not send mail to: " + to + ", System Exception - " + e);
            //HashMap errors = new HashMap();
            m_errors.put ("Could not send a mail", null );
            request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
        }
        finally {
            if (fWriter != null) {
                try { fWriter.close(); } catch (IOException ignore) {}
            }

            // DELETE THE TEMPORARY ATTACHMENT FILE
            if (psAttachment != null) {
                psAttachment.delete();
            }
        }
    }


	/*private void repeatedPartNumbers ( ArrayList orderLineItemList, HttpSession session )
	{
		ArrayList repetedPartNumber = new ArrayList();
		if( orderLineItemList.size() > 1)
		{
			for( int i=0 ; i < orderLineItemList.size()-1 ; i++ )
			{
				LineItem lineItem = (LineItem) orderLineItemList.get(i);
				String partNumber = lineItem.getManufacturingPartNo();

				for(int j=i+1 ; j < orderLineItemList.size(); j++)
				{
					LineItem secLineItem = (LineItem) orderLineItemList.get(j);

					String secPartNumber = secLineItem.getManufacturingPartNo();

					if(partNumber.equalsIgnoreCase(secPartNumber))
					{
						if( !repetedPartNumber.contains(lineItem.getLineItemId()+"") )
							repetedPartNumber.add(lineItem.getLineItemId()+"");
						if( !repetedPartNumber.contains(secLineItem.getLineItemId()+"") )
							repetedPartNumber.add(secLineItem.getLineItemId()+"");
					}
				}
			}
		}
		if( repetedPartNumber.size() > 0 )
		{
			session.setAttribute("repetedPartNumber",repetedPartNumber);
		}
	} */
}